using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Framework.Core;

namespace WorldMapBase.Tile.Pool
{
    /// <summary>
    /// 沙盘动态层的对象池管理器
    /// </summary>
    public class WorldDynamicPoolMgr: SingletonMono<WorldDynamicPoolMgr>
    {
        public static Transform InstanceRoot;

        public static Transform GetInstanceRoot()
        {
            return InstanceRoot;
        }

        private Dictionary<int, DynamicPrefabPool> _dynamicPrefabPools;
        
        public void OnInit()
        {
            this.transform.SetParent(PoolCollectionManager.GetInstance("PoolCollectionManager").transform);

            if (InstanceRoot == null)
            {
                InstanceRoot = (new GameObject("InstanceRoot")).transform;
                InstanceRoot.SetParent(this.transform);
            }
            Initialize();
        }

        public override void Initialize(Options options = null)
        {
            base.Initialize(options);
            _dynamicPrefabPools = new Dictionary<int, DynamicPrefabPool>();
        }

        public void AddDynamicPrefabPool(int poolID,int initNum,int capacity,GameObject originObject)
        {
            DynamicPrefabPool dynamicPrefabPool = new DynamicPrefabPool(initNum,capacity,originObject);
            dynamicPrefabPool.PreInit();
            _dynamicPrefabPools[poolID] = dynamicPrefabPool;
        }


        public Transform GetDynamicItem(int poolID)
        {

            Transform t = null;
            //int index = 0;
            //while (t == null && index < 10)
            {
                t = _dynamicPrefabPools[poolID].GetItem();
            }

            if (t == null)
            {
                Debug.LogError("尝试获取的物体被销毁");   
            }
            return t;
        }

        public void RecoverDynamicItem(int poolID, Transform obj,bool resetParent)
        {
            _dynamicPrefabPools[poolID].RecoverItem(obj);
            if (resetParent)
            {
                obj.parent = InstanceRoot;
            }
        }


        public void DestroyPool()
        {
            foreach (var p in _dynamicPrefabPools)
            {
                p.Value.Destroy();
            }
            _dynamicPrefabPools.Clear();

            Dispose();
        }
    }
}
